package bar.dark.lee.select;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.KeyValueAdapter;
import bar.dark.lee.common.KeyValueData;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.setting.auto.AutoInsertActivity;

public class SelectInfoActivity extends SuperActivity
{
	private boolean ERROR = false;
	
	private DBSQLite sql;
	
	private ListView listView;
	
	private View buttonView;
	
	private Button deleteButton;
	private Button updateButton;
	private View alertView;
	
	private SelectData data;
	private SelectSubData subData;
	
	private int banklink = -1;
	
	private ArrayList<KeyValueData> list;
	
	private String balanceMoney = "";
	private String realMoney = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		super.setGoneTipButton();
		
		sql = DBSQLite.getInstance(this);
		
		setTitle("내역 상세 조회");
		
		setContentView(R.layout.select_info_activity);
		setFindView();
		setClickListener();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(0);
	}
	
	private void setFindView()
	{
		buttonView = findViewById(R.id.selectInfoButtonView);
		deleteButton = (Button) findViewById(R.id.selectInfoDeleteButton);
		updateButton = (Button) findViewById(R.id.selectInfoUpdateButton);
		alertView = findViewById(R.id.selectInfoViewAlert);
		listView = (ListView) findViewById(R.id.selectInfoListView);
		listView.setVerticalFadingEdgeEnabled(true);
		listView.setFooterDividersEnabled(false);
	}

	private void setData()
	{
		Intent intent = getIntent();
		data = intent.getParcelableExtra(SelectActivity.SELECT_DATA);
		
		if (data == null) 
		{
			ERROR = true;
			return;
		}
		
		setSelectInfoData();
		
		if (data == null) 
		{
			ERROR = true;
			return;
		}
		
		list = new ArrayList<KeyValueData>();
		
		if (data.getType().equals(BDConstents.REAL_TYPE))
		{
			BDUtil.getKeyValueData(list, "타입", BDConstents.REAL_MONEY);
		}
		else if (data.getType().equals(BDConstents.BANK_TYPE))
		{
			BDUtil.getKeyValueData(list, "타입", BDConstents.BANK_MONEY);
			
			BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
		}
		else if (data.getType().equals(BDConstents.CHECK_TYPE))
		{
			BDUtil.getKeyValueData(list, "타입", BDConstents.CHECK_CARD);
			
			BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
		}
		else if (data.getType().equals(BDConstents.CREDIT_TYPE))
		{
			BDUtil.getKeyValueData(list, "타입", BDConstents.CREDIT_CARD);
			
			BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
		}
		else if (data.getType().equals(BDConstents.INOUT_TYPE))
		{
			BDUtil.getKeyValueData(list, "타입", BDConstents.BANK_TO_REAL);
			
			if (data.getLinktype().equals(BDConstents.BANK_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.BANK_MONEY);
			}
			else if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.CHECK_CARD);
			}
			else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.CREDIT_CARD);
			}
			
			BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
		}
		else if (data.getType().equals(BDConstents.OUTIN_TYPE))
		{
			BDUtil.getKeyValueData(list, "타입", BDConstents.REAL_TO_BANK);
			
			if (data.getLinktype().equals(BDConstents.BANK_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.BANK_MONEY);
			}
			else if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.CHECK_CARD);
			}
			
			BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
		}
		else if (data.getType().equals(BDConstents.FAN_TYPE))
		{
			BDUtil.getKeyValueData(list, "타입", BDConstents.FAN_MONEY);
			
			if (data.getLinktype().equals(BDConstents.REAL_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.REAL_MONEY);
			}
			else if (data.getLinktype().equals(BDConstents.BANK_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.BANK_MONEY);
				BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
			}
			else if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.CHECK_CARD);
				BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
			}
			else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.CREDIT_CARD);
				BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
			}
		}
		else if (data.getType().equals(BDConstents.MYBANK_INOUT_TYPE))
		{
			BDUtil.getKeyValueData(list, "타입", BDConstents.MYBANK_INOUT);
			
			if (data.getLinktype().equals(BDConstents.BANK_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.BANK_MONEY);
				BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
			}
			else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
			{
				BDUtil.getKeyValueData(list, "종류", BDConstents.CREDIT_CARD);
				BDUtil.getKeyValueData(list, "이름", data.getMoneyKind());
			}
		}
		
		// 자산이름이 null 일 경우에는 현금을 넣어준다.
		String moneyKind = data.getMoneyKind();
		
		if (moneyKind == null || data.getType().equals(BDConstents.REAL_TYPE))
		{
			moneyKind = BDConstents.REAL_MONEY;
		}
		
		BalanceQuery balanceQuery = new BalanceQuery(superContext);
		
		BDUtil.getKeyValueData(list, moneyKind + "잔액", balanceQuery.getBalanceMoney(data.getId()));
		
		if (data.getType().equals(BDConstents.OUTIN_TYPE) || data.getType().equals(BDConstents.INOUT_TYPE))
		{
			BDUtil.getKeyValueData(list, "현금잔액", balanceQuery.getRealMoney(data.getId()));
		}
		
		BDUtil.getKeyValueData(list, "카테고리", data.getCategory());
		
		BDUtil.getKeyValueData(list, "날짜", BDUtil.getDateButton(data.getDate()));
		
		if (!data.getInMoney().equals("0"))
		{
			BDUtil.getKeyValueData(list, "수입", BDUtil.getWon(data.getInMoney()) + shape);
		}
		
		if (!data.getOutMoney().equals("0"))
		{
			BDUtil.getKeyValueData(list, "지출", BDUtil.getWon(data.getOutMoney()) + shape);
		}
		
		if (!data.getPostMoney().equals("0"))
		{
			BDUtil.getKeyValueData(list, "카드대금", BDUtil.getWon(data.getPostMoney()) + shape);
		}
		
		BDUtil.getKeyValueData(list, "내용", data.getMemo());
	}
	
	/**
	 * 데이터를 새로 가져온다.
	 */
	private void setSelectInfoData()
	{
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE id = " + data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				data = new SelectData();
				
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoneykind = c.getColumnIndex("postmoneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				int deleteyn = c.getColumnIndex("deleteyn");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					data.setId(c.getInt(id) + "");
					data.setCategory(c.getString(category));
					data.setMemo(c.getString(memo));
					data.setInMoney(c.getString(inmoney));
					data.setOutMoney(c.getString(outmoney));
					data.setPostMoney(c.getString(postmoney));
					data.setDate(c.getInt(date) + "");
					data.setMoneyKind(c.getString(moneykind));
					data.setPostMoneyKind(c.getString(postmoneykind));
					data.setType(c.getInt(type) + "");
					data.setLinkId(c.getInt(linkid) + "");
					data.setLinktype(c.getInt(linktype) + "");
					data.setDeleteYn(c.getInt(deleteyn) + "");
					
					c.moveToNext();
				}
			}
		});
	}

	private void setClickListener()
	{
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
//				if (isPostMoneyComplete()) {
//					BDUtil.showDialog(SelectInfoActivity.this, "삭제 오류", "이 내역에 대한 카드대금결제가 완료되었습니다. 먼저 카드대금결제 내역을 삭제해주세요.");
//					return;
//				}
				
				AlertDialog.Builder dialog = new AlertDialog.Builder(SelectInfoActivity.this);
				dialog.setIcon(android.R.drawable.ic_dialog_alert);
		    	dialog.setTitle("삭제");
		    	dialog.setMessage("데이터를 삭제 하시겠습니까?");
		    	dialog.setPositiveButton("삭제", new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						new ShowDialog().execute(1);
						dialog.dismiss();
					}
				});
		    	dialog.setNegativeButton("취소", new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
					}
				});
		    	
		    	dialog.show();
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
//				if (isPostMoneyComplete()) {
//					BDUtil.showDialog(SelectInfoActivity.this, "수정 오류", "이 내역에 대한 카드대금결제가 완료되었습니다. 먼저 카드대금결제 내역을 삭제해주세요.");
//					return;
//				}
				
				Intent intent = new Intent(SelectInfoActivity.this, SelectUpdateActivity.class);
				intent.putExtra(SelectActivity.SELECT_DATA, data);
				startActivity(intent);
			}
		});
	}
	
	private boolean postMoneyComplete = false;
	private boolean isPostMoneyComplete() 
	{
		
		postMoneyComplete = false;
		
		sql.selectMapTile(this, "SELECT id FROM in_out WHERE date > " + data.getDate() + " and category = '" + 
						BDConstents.CATEGORY_POST_OUT + "' and postmoneykind = '"
						+ BDUtil.getApostrophe(data.getMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				c.moveToFirst();
				
				if (c.getCount() == 0) {
					postMoneyComplete = false;
				} else {
					postMoneyComplete = true;
				}
				
			}
		});
		
		return postMoneyComplete;
	}
	
	/**
	 * 데이터를 삭제 하고 난후 롤백 시킨다.
	 */
	private void setRollBackData()
	{
		if (data.getType().equals(BDConstents.REAL_TYPE) || data.getDeleteYn().equals("1")) // 현금
		{
			setRealMoneyRollBack(data);
		}
		else if (data.getType().equals(BDConstents.BANK_TYPE)) // 통장
		{
			setBankMoneyRollBack(data);
			
			if (data.getCategory().equals(BDConstents.CATEGORY_POST_OUT)) 
			{
				setPostMoneyRollBack();
			}
		}
		else if (data.getType().equals(BDConstents.CHECK_TYPE)) // 체크카드
		{
			setCheckCardRollBack();
		}
		else if (data.getType().equals(BDConstents.CREDIT_TYPE)) // 신용카드
		{
			setCreditCardRollBack(data);
		}
		else if (data.getType().equals(BDConstents.INOUT_TYPE)) // 현금인출
		{
			// 인출 데이터 롤백
			setInOutRollBack(data);
			
			// 현금인출일 경우
			if (!data.getCategory().equals(BDConstents.CATEGORY_SUSUMONEY))
			{
				// 현금 데이터 롤백
				setInOutRealMoneyRollBack();
				
				// 수수료 데이터 롤백
				setCommRollBack();
			}
		}
		else if (data.getType().equals(BDConstents.OUTIN_TYPE)) // 현금입금
		{
			setOutInRollBank();
		}
		else if (data.getType().equals(BDConstents.MYBANK_INOUT_TYPE)) // 내통장이체
		{
			if (data.getLinktype().equals(BDConstents.BANK_TYPE))
			{
				setBankMoneyRollBack(data);
			}
			else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
			{
				setCreditCardRollBack(data);
			}
			
			if (!data.getCategory().equals(BDConstents.CATEGORY_SUSUMONEY))
			{
				setSusuRollBank();
				setLinkIdRollBank();
				setSusuRollBank();
			}
		}
	}
	
	private void setSusuRollBank()
	{
		// 수수료 데이터를 롤백한다.
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE linkid = " 
				+ data.getId() + " and category = '" 
				+ BDConstents.CATEGORY_SUSUMONEY + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				int deleteYN = c.getColumnIndex("deleteyn");
				
				c.moveToFirst();
				
				SelectData selectData =	null;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					selectData = new SelectData();
					selectData.setId(c.getInt(id) + "");
					selectData.setCategory(c.getString(category));
					selectData.setMemo(c.getString(memo));
					selectData.setInMoney(c.getString(inmoney));
					selectData.setOutMoney(c.getString(outmoney));
					selectData.setPostMoney(c.getString(postmoney));
					selectData.setDate(c.getInt(date) + "");
					selectData.setMoneyKind(c.getString(moneykind));
					selectData.setType(c.getInt(type) + "");
					selectData.setLinkId(c.getInt(linkid) + "");
					selectData.setLinktype(c.getInt(linktype) + "");
					selectData.setDeleteYn(c.getInt(deleteYN) + "");
					
					c.moveToNext();
				}
				
				if (selectData != null)
				{
					setInOutRollBack(selectData);
					
					String [] whereArgs = new String[]{selectData.getId()};
					sql.delete(SelectInfoActivity.this, "in_out", "id = ?", whereArgs);
				}
				
			}
		});
	}

	private void setLinkIdRollBank()
	{
		// 내통장이체 데이터를 롤백한다.
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE id = " 
				+ data.getLinkId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				int deleteYN = c.getColumnIndex("deleteyn");
				
				c.moveToFirst();
				
				SelectData selectData =	null;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					// 날짜가 다른 경우 다음 리스트로 셋팅한다.
					selectData = new SelectData();
					selectData.setId(c.getInt(id) + "");
					selectData.setCategory(c.getString(category));
					selectData.setMemo(c.getString(memo));
					selectData.setInMoney(c.getString(inmoney));
					selectData.setOutMoney(c.getString(outmoney));
					selectData.setPostMoney(c.getString(postmoney));
					selectData.setDate(c.getInt(date) + "");
					selectData.setMoneyKind(c.getString(moneykind));
					selectData.setType(c.getInt(type) + "");
					selectData.setLinkId(c.getInt(linkid) + "");
					selectData.setLinktype(c.getInt(linktype) + "");
					selectData.setDeleteYn(c.getInt(deleteYN) + "");
					
					c.moveToNext();
				}
				
				if (selectData != null)
				{
					if (data.getDeleteYn().equals("1"))
					{
						setRealMoneyRollBack(selectData);
					}
					else if (data.getLinktype().equals(BDConstents.BANK_TYPE))
					{
						setBankMoneyRollBack(selectData);
					}
					else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
					{
						setCreditCardRollBack(selectData);
					}
					
					String [] whereArgs = new String[]{selectData.getId()};
					sql.delete(SelectInfoActivity.this, "in_out", "id = ?", whereArgs);
				}
				
			}
		});
	}

	/**
	 * 현금입금 데이터를 롤백한다.
	 */
	private void setOutInRollBank()
	{
		// 현금테이블을 롤백한다.
		sql.selectMapTile(this, "SELECT money FROM real_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				money = money.add(new BigDecimal(data.getInMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				sql.update(SelectInfoActivity.this, "real_money", map, null, null);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.REAL_TYPE, 
						BDConstents.REAL_MONEY, data.getInMoney(), 1);
			}
		});
		
		if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
		{
			int id = getCheckCardId(data.getMoneyKind());
			
			setRollBankBankBook(id);
		}
		else if (data.getLinktype().equals(BDConstents.BANK_TYPE))
		{
			setRollBackBankBook(data.getMoneyKind());
		}
	}

	/**
	 * 통장에 금액을 뺀다.
	 * @param moneyKind
	 */
	private void setRollBackBankBook(final String moneyKind)
	{
		sql.selectMapTile(this, "SELECT id, money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(moneyKind) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				int idIdx = c.getColumnIndex("id");
				
				BigDecimal money = BigDecimal.ZERO;
				int id = -1;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				money = money.subtract(new BigDecimal(data.getInMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				sql.update(SelectInfoActivity.this, "bankbook", map, "id = ?", whereArgs);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.BANK_TYPE, 
						moneyKind, data.getInMoney(), 0);
			}
		});
	}

	/**
	 * 통장에 금액을 뺀다.
	 * @param id
	 */
	private void setRollBankBankBook(int id)
	{
		sql.selectMapTile(this, "SELECT id, money FROM bankbook WHERE id = "
				+ id + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				int idIdx = c.getColumnIndex("id");
				
				BigDecimal money = BigDecimal.ZERO;
				int id = -1;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				money = money.subtract(new BigDecimal(data.getInMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				sql.update(SelectInfoActivity.this, "bankbook", map, "id = ?", whereArgs);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.CHECK_TYPE, 
						data.getMoneyKind(), data.getInMoney(), 0);
			}
		});
	}

	/**
	 * 체크카드에 연결된 통장 아이디를 가져온다.
	 * @param moneyKind
	 * @return
	 */
	private int getCheckCardId(String moneyKind)
	{
		banklink = -1;
		
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '"
				+ BDUtil.getApostrophe(moneyKind) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int banklinkIdx = c.getColumnIndex("banklink");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					banklink = c.getInt(banklinkIdx);
					c.moveToNext();
				}
			}
		});
		
		return banklink;
	}

	/**
	 * 수수료 데이터를 롤백한다.
	 */
	private void setCommRollBack()
	{
		// 링크 아이디가 없으면 연결된 데이터를 지우지 않는다.
		if (Integer.parseInt(data.getLinkId()) < 0)
		{
			return;
		}
		
		// 수수료 데이터를 롤백한다.
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE id = " 
				+ data.getLinkId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				int deleteYN = c.getColumnIndex("deleteyn");
				
				c.moveToFirst();
				
				SelectData selectData =	null;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					// 날짜가 다른 경우 다음 리스트로 셋팅한다.
					selectData = new SelectData();
					selectData.setId(c.getInt(id) + "");
					selectData.setCategory(c.getString(category));
					selectData.setMemo(c.getString(memo));
					selectData.setInMoney(c.getString(inmoney));
					selectData.setOutMoney(c.getString(outmoney));
					selectData.setPostMoney(c.getString(postmoney));
					selectData.setDate(c.getInt(date) + "");
					selectData.setMoneyKind(c.getString(moneykind));
					selectData.setType(c.getInt(type) + "");
					selectData.setLinkId(c.getInt(linkid) + "");
					selectData.setLinktype(c.getInt(linktype) + "");
					selectData.setDeleteYn(c.getInt(deleteYN) + "");
					
					c.moveToNext();
				}
				
				if (selectData != null)
				{
					setInOutRollBack(selectData);
					
					String [] whereArgs = new String[]{selectData.getId()};
					sql.delete(SelectInfoActivity.this, "in_out", "id = ?", whereArgs);
				}
				
			}
		});
	}

	private void setInOutRealMoneyRollBack()
	{
		String query;
		// 현금에서 돈을 뺀다.
		query = "SELECT money FROM real_money;";
		
		sql.selectMapTile(this, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal totalMoney = BigDecimal.ZERO;
				int moneyIndex = c.getColumnIndex("money");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					totalMoney = totalMoney.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				String rollMoney = "0";
				
				HashMap<String, String> map = new HashMap<String, String>();
				
				if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
				{
					totalMoney = totalMoney.subtract(new BigDecimal(data.getPostMoney()));
					rollMoney = data.getPostMoney();
				}
				else
				{
					totalMoney = totalMoney.subtract(new BigDecimal(data.getOutMoney()));
					rollMoney = data.getOutMoney();
				}
				
				map.put("money", totalMoney.toString());
				sql.update(SelectInfoActivity.this, "real_money", map, null, null);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.REAL_TYPE, 
						BDConstents.REAL_MONEY, rollMoney.toString(), 0);
			}
		});
	}

	private void setInOutRollBack(final SelectData data)
	{
		String query = "";
		
		// 통장에 돈을 넣는다.
		if (data.getLinktype().equals(BDConstents.BANK_TYPE))
		{
			query = "SELECT money FROM bankbook WHERE name = '" + BDUtil.getApostrophe(data.getMoneyKind()) + "';";
			
			sql.selectMapTile(this, query, new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					BigDecimal money = BigDecimal.ZERO;
					int moneyIndex = c.getColumnIndex("money");
					c.moveToFirst();
					for (int i = 0; i < c.getCount(); i++)
					{
						money = money.add(new BigDecimal(c.getString(moneyIndex)));
						c.moveToNext();
					}
					
					HashMap<String, String> map = new HashMap<String, String>();
					
					money = money.add(new BigDecimal(data.getOutMoney()));
					
					map.put("money", money.toString());
					
					String [] whereArgs = new String[]{data.getMoneyKind()};
					sql.update(SelectInfoActivity.this, "bankbook", map, "name = ?", whereArgs);
					
					BalanceQuery balanceQuery = new BalanceQuery(superContext);
					balanceQuery.setbalanceDelete(data.getId(), BDConstents.BANK_TYPE, 
							data.getMoneyKind(), data.getOutMoney(), 1);
				}
			});
		}
		// 체크카드에 돈을 넣는다.
		else if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
		{
			query = "SELECT banklink FROM check_card WHERE name = '" + BDUtil.getApostrophe(data.getMoneyKind()) + "';";
			
			sql.selectMapTile(this, query, new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					banklink = -1;
					int banklinkIndex = c.getColumnIndex("banklink");
					c.moveToFirst();
					for (int i = 0; i < c.getCount(); i++)
					{
						banklink = c.getInt(banklinkIndex);
						c.moveToNext();
					}
					
				}
			});
			
			sql.selectMapTile(SelectInfoActivity.this, "SELECT money FROM bankbook WHERE id = "
					+ banklink + ";", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					BigDecimal money = BigDecimal.ZERO;
					int moneyIndex = c.getColumnIndex("money");
					c.moveToFirst();
					for (int i = 0; i < c.getCount(); i++)
					{
						money = money.add(new BigDecimal(c.getString(moneyIndex)));
						c.moveToNext();
					}
					
					HashMap<String, String> map = new HashMap<String, String>();
					
					money = money.add(new BigDecimal(data.getOutMoney()));
					
					map.put("money", money.toString());
					
					String [] whereArgs = new String[]{banklink + ""};
					sql.update(SelectInfoActivity.this, "bankbook", map, "id = ?", whereArgs);
					
					BalanceQuery balanceQuery = new BalanceQuery(superContext);
					balanceQuery.setbalanceDelete(data.getId(), BDConstents.CHECK_TYPE, 
							data.getMoneyKind(), data.getOutMoney(), 1);
				}
			});
		}
		// 신용카드에 돈을 넣는다.
		else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
		{
			query = "SELECT outmoney FROM credit_card WHERE name = '" + BDUtil.getApostrophe(data.getMoneyKind()) + "';";
			
			sql.selectMapTile(this, query, new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					BigDecimal outmoney = BigDecimal.ZERO;
					int outmoneyIndex = c.getColumnIndex("outmoney");
					c.moveToFirst();
					for (int i = 0; i < c.getCount(); i++)
					{
						outmoney = outmoney.add(new BigDecimal(c.getString(outmoneyIndex)));
						c.moveToNext();
					}
					
					HashMap<String, String> map = new HashMap<String, String>();
					
					outmoney = outmoney.subtract(new BigDecimal(data.getPostMoney()));
					
					map.put("outmoney", outmoney.toString());
					
					String [] whereArgs = new String[]{data.getMoneyKind()};
					sql.update(SelectInfoActivity.this, "credit_card", map, "name = ?", whereArgs);
					
					BalanceQuery balanceQuery = new BalanceQuery(superContext);
					balanceQuery.setbalanceDelete(data.getId(), BDConstents.CREDIT_TYPE, 
							data.getMoneyKind(), data.getPostMoney(), 0);
				}
			});
		}
	}

	/**
	 * 현금으로 된 데이터를 롤백시킨다.
	 */
	private void setRealMoneyRollBack(final SelectData data)
	{
		sql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal money = BigDecimal.ZERO;
				int moneyIndex = c.getColumnIndex("money");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				int flag = 0;
				String rollMoney = "0";
				
				HashMap<String, String> map = new HashMap<String, String>();
				
				if (!data.getInMoney().equals("0"))
				{
					money = money.subtract(new BigDecimal(data.getInMoney()));
					rollMoney = data.getInMoney();
					flag = 0;
				}
				else if (!data.getOutMoney().equals("0"))
				{
					money = money.add(new BigDecimal(data.getOutMoney()));
					rollMoney = data.getOutMoney();
					flag = 1;
				}
				
//				if (!data.getPostMoney().equals("0"))
//				{
//					if (!data.getType().equals(BDConstents.INOUT_TYPE))
//					{
//						money = money.add(new BigDecimal(data.getPostMoney()));
//						flag = 1;
//					}
//				}
				
				map.put("money", money.toString());
				
				sql.update(SelectInfoActivity.this, "real_money", map, null, null);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.REAL_TYPE, 
						BDConstents.REAL_MONEY, rollMoney.toString(), flag);
			}
		});
	}
	
	/**
	 * 통장으로 된 데이터를 롤백시킨다.
	 */
	private void setBankMoneyRollBack(final SelectData data)
	{
		sql.selectMapTile(this, "SELECT money FROM bankbook WHERE name = '" 
				+ BDUtil.getApostrophe(data.getMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal money = BigDecimal.ZERO;
				int moneyIndex = c.getColumnIndex("money");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				int flag = 0;
				String rollMoney = "0";
				
				HashMap<String, String> map = new HashMap<String, String>();
				
				if (data.getInMoney().equals("0"))
				{
					money = money.add(new BigDecimal(data.getOutMoney()));
					rollMoney = data.getOutMoney();
					flag = 1;
				}
				else if (data.getOutMoney().equals("0"))
				{
					money = money.subtract(new BigDecimal(data.getInMoney()));
					rollMoney = data.getInMoney();
					flag = 0;
				}
				
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{data.getMoneyKind()};
				sql.update(SelectInfoActivity.this, "bankbook", map, "name = ?", whereArgs);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.BANK_TYPE, 
						data.getMoneyKind(), rollMoney.toString(), flag);
			}
		});
	}
	
	/**
	 * 체크카드 데이터를 롤백시킨다.
	 */
	private void setCheckCardRollBack()
	{
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '" 
				+ BDUtil.getApostrophe(data.getMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				banklink = -1;
				int banklinkIndex = c.getColumnIndex("banklink");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					banklink = c.getInt(banklinkIndex);
					c.moveToNext();
				}
				
			}
		});
		
		if (banklink > -1)
		{
			sql.selectMapTile(SelectInfoActivity.this, "SELECT money FROM bankbook WHERE id = " 
					+ banklink + ";", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					BigDecimal money = BigDecimal.ZERO;
					int moneyIndex = c.getColumnIndex("money");
					c.moveToFirst();
					for (int i = 0; i < c.getCount(); i++)
					{
						money = money.add(new BigDecimal(c.getString(moneyIndex)));
						c.moveToNext();
					}
					
					int flag = 0;
					String rollMoney = "0";
					
					HashMap<String, String> map = new HashMap<String, String>();
					
					if (data.getInMoney().equals("0"))
					{
						money = money.add(new BigDecimal(data.getOutMoney()));
						rollMoney = data.getOutMoney();
						flag = 1;
					}
					else if (data.getOutMoney().equals("0"))
					{
						money = money.subtract(new BigDecimal(data.getInMoney()));
						rollMoney = data.getInMoney();
						flag = 0;
					}
					
					map.put("money", money.toString());
					
					String [] whereArgs = new String[]{banklink + ""};
					sql.update(SelectInfoActivity.this, "bankbook", map, "id = ?", whereArgs);
					
					BalanceQuery balanceQuery = new BalanceQuery(superContext);
					balanceQuery.setbalanceDelete(data.getId(), BDConstents.CHECK_TYPE, 
							data.getMoneyKind(), rollMoney.toString(), flag);
				}
			});
		}
	}
	
	/**
	 * 신용카드 데이터를 롤백 시킨다.
	 */
	private void setCreditCardRollBack(final SelectData data)
	{
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '" 
				+ BDUtil.getApostrophe(data.getMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal outmoney = BigDecimal.ZERO;
				int outmoneyIndex = c.getColumnIndex("outmoney");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					outmoney = outmoney.add(new BigDecimal(c.getString(outmoneyIndex)));
					c.moveToNext();
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				
				outmoney = outmoney.subtract(new BigDecimal(data.getPostMoney()));
				
				map.put("outmoney", outmoney.toString());
				
				String [] whereArgs = new String[]{data.getMoneyKind()};
				sql.update(SelectInfoActivity.this, "credit_card", map, "name = ?", whereArgs);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.CREDIT_TYPE, 
						data.getMoneyKind(), data.getPostMoney(), 0);
			}
		});
	}
	
	private void setPostMoneyRollBack() 
	{
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '" 
				+ BDUtil.getApostrophe(data.getPostMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal outmoney = BigDecimal.ZERO;
				int outmoneyIndex = c.getColumnIndex("outmoney");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					outmoney = outmoney.add(new BigDecimal(c.getString(outmoneyIndex)));
					c.moveToNext();
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				
				outmoney = outmoney.add(new BigDecimal(data.getOutMoney()));
				
				map.put("outmoney", outmoney + "");
				
				String [] whereArgs = new String[]{data.getPostMoneyKind()};
				sql.update(SelectInfoActivity.this, "credit_card", map, "name = ?", whereArgs);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == Activity.RESULT_OK)
		{
			finish();
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(SelectInfoActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setData();
				return 0;
			}
			else if (arg0[0] == 1)
			{
				try
				{
					sql.beginTansaction(superContext);
					
					setRollBackData();
					
					String [] whereArgs = new String[]{data.getId()};
					sql.delete(SelectInfoActivity.this, "in_out", "id = ?", whereArgs);
					
					sql.setTransactionSuccessful();
				} catch (Exception e)
				{
					return -1;
				} finally {
					try 
					{
						sql.endTransaction(superContext);
					} catch (Exception e) 
					{
						return -1;
					}
				}
				
				return 1;
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 0)
			{
				if (ERROR) 
				{
					BDUtil.showDialogFinish(SelectInfoActivity.this,
							"오류", "데이터 로딩에 실패했습니다. 다시 시도해 주세요. ㅠㅠ");
					return;
				}
				
				KeyValueAdapter adapter = new KeyValueAdapter(
						SelectInfoActivity.this, R.layout.list_item_key_value, list);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				
				if (data.getType().equals(BDConstents.FAN_TYPE))
				{
					buttonView.setVisibility(View.GONE);
					alertView.setVisibility(View.VISIBLE);
					ViewGroup vg = (ViewGroup) alertView;
					TextView tv = (TextView) vg.getChildAt(0);
					tv.setText("부채 내역은 부채 메뉴에 가서 수정해주세요~^^");
				}
				else if (data.getDeleteYn().equals("1"))
				{
					buttonView.setVisibility(View.VISIBLE);
					deleteButton.setVisibility(View.VISIBLE);
					updateButton.setVisibility(View.GONE);
					
					alertView.setVisibility(View.VISIBLE);
					ViewGroup vg = (ViewGroup) alertView;
					TextView tv = (TextView) vg.getChildAt(0);
					tv.setText("통장/카드가 삭제 되었습니다. 삭제시에 금액 변동이 현금으로 적용됩니다.");
				}
				else
				{
					alertView.setVisibility(View.GONE);
					buttonView.setVisibility(View.VISIBLE);
					deleteButton.setVisibility(View.VISIBLE);
					updateButton.setVisibility(View.VISIBLE);
				}
			}
			else if (result == 1)
			{
				BDUtil.showDialogFinish(SelectInfoActivity.this,
						"확인", "데이터가 삭제 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
//		Intent intent = new Intent(this, TipInfoActivity.class);
//		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_DELETE);
//		startActivity(intent);
	}
}
